package com.zyk.scaffold.core.arthas;

import com.taobao.arthas.agent.attach.ArthasAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.HashMap;

@Configuration
public class ArthasAgentConfigration {

    @Autowired
    ConfigurableEnvironment environment;

    @Bean
    public ArthasAgent arthasAgent() {
        HashMap<String, String> configMap = new HashMap<String, String>();
        String appName = environment.getProperty("server-id");
        if (appName == null) {
            appName = environment.getProperty("spring.application.name");
        }
        configMap.put("arthas.appName", appName);

        String tunnelServer = environment.getProperty("arthas-tunnel-server");
        if (tunnelServer == null) {
            tunnelServer = "ws://127.0.0.1:7777/ws";
        }

        String ipAddress = environment.getProperty("spring.cloud.client.ip-address");
        if (ipAddress == null) {
            ipAddress = "127.0.0.1";
        }

        Integer port = environment.getProperty("server.port", Integer.class, 8080);

        configMap.put("arthas.telnetPort", String.valueOf(port + 3000));
        configMap.put("arthas.httpPort", String.valueOf(port + 4000));
        configMap.put("arthas.appName", appName);
        configMap.put("arthas.tunnelServer", tunnelServer);
        configMap.put("arthas.agentId", appName + "_" + ipAddress + ":" + port);

        final ArthasAgent arthasAgent = new ArthasAgent(configMap, environment.getProperty("arthas.home"),
                environment.getProperty("arthas.slientInit", Boolean.class, false), null);
        arthasAgent.init();
        return arthasAgent;
    }
}
